package com.example.actflow.view;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.actflow.R;
import com.example.actflow.eum.ActionType;
import com.example.actflow.eum.CompareOp;
import com.example.actflow.repository.ContextData;
import com.example.actflow.model.LogicItem;


import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

public class FileExplorerView extends LinearLayout {

    private ContextData contextData;

    private LinearLayout pathContainer;
    private RecyclerView fileRecyclerView;
    private Button addConfigButton;

    private List<LogicItem> pathStack = new ArrayList<>();


    public FileExplorerView(Context context) {
        super(context);
        contextData = ContextData.getInstance(context);
        init(context);
    }

    public FileExplorerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        contextData = ContextData.getInstance(context);
        init(context);

    }

    private void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.view_file_explorer, this, true);

        pathContainer = findViewById(R.id.path_container);
        fileRecyclerView = findViewById(R.id.file_recycler_view);
        addConfigButton = findViewById(R.id.addConfig);

        pathStack.add(contextData.getRoot());
        renderPath();
        renderList();

        addConfigButton.setOnClickListener(v -> showAddDialog(null));
    }

    private void renderPath() {
        pathContainer.removeAllViews();
        for (int i = 0; i < pathStack.size(); i++) {
            LogicItem item = pathStack.get(i);
            TextView segment = new TextView(getContext());
            segment.setText(item.varName != null ? item.varName : item.param);
            segment.setTextColor(Color.WHITE);
            segment.setTextSize(16);
            segment.setPadding(8, 0, 8, 0);
            final int finalI = i;
            segment.setOnClickListener(v -> {
                while (pathStack.size() > finalI + 1) pathStack.remove(pathStack.size() - 1);
                contextData.setCurrentList(pathStack.get(finalI).children);
                renderPath();
                renderList();
            });
            pathContainer.addView(segment);

            if (i < pathStack.size() - 1) {
                TextView sep = new TextView(getContext());
                sep.setText(" > ");
                sep.setTextColor(Color.WHITE);
                sep.setPadding(4, 0, 4, 0);
                pathContainer.addView(sep);
            }
        }
    }

    private void renderList() {
        fileRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        fileRecyclerView.setAdapter(new RecyclerView.Adapter<>() {
            @Override
            public int getItemCount() {
                return contextData.getCurrentList().size();
            }

            @NonNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext())
                        .inflate(android.R.layout.simple_list_item_1, parent, false);
                return new RecyclerView.ViewHolder(view) {
                };
            }

            @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                LogicItem item = contextData.getCurrentList().get(position);
                TextView tv = (TextView) holder.itemView;
                tv.setText(item.toString());

                tv.setOnClickListener(v -> {
                    if (item.isFolder()) {
                        pathStack.add(item);
                        contextData.setCurrentList(item.children);
                        renderPath();
                        renderList();
                    }
                });

                tv.setOnLongClickListener(v -> {
                    new AlertDialog.Builder(getContext())
                            .setItems(new CharSequence[]{"修改", "删除"}, (dialog, which) -> {
                                if (which == 0) {
                                    showAddDialog(item);
                                } else {
                                    contextData.getCurrentList().remove(position);
                                    renderList();
                                    contextData.saveConfigForApp();
                                }
                            }).show();
                    return true;
                });
            }
        });
        fileRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
    }

    @SuppressLint("SetTextI18n")
    private void showAddDialog(@Nullable LogicItem itemToEdit) {
        View dialogView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_add_config, null);

        AlertDialog dialog = new AlertDialog.Builder(getContext())
                .setTitle(itemToEdit == null ? "添加节点" : "修改节点")
                .setView(dialogView)
                .setPositiveButton("确定", null)
                .setNegativeButton("取消", null)
                .create();

        dialog.setOnShowListener(dialogInterface -> {
            Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);

            Spinner typeSpinner = dialogView.findViewById(R.id.typeSpinner);
            Spinner targetSpinner = dialogView.findViewById(R.id.targetSpinner);
            Spinner compareOpSpinner = dialogView.findViewById(R.id.compareOpSpinner);
            Spinner actionSelectSpinner = dialogView.findViewById(R.id.actionSelectSpinner);

            EditText paramInput = dialogView.findViewById(R.id.paramInput);
            EditText variableName = dialogView.findViewById(R.id.variableName);
            EditText delayInput = dialogView.findViewById(R.id.delayInput);

            LinearLayout variableLayout = dialogView.findViewById(R.id.variableLayout);
            LinearLayout compareOpLayout = dialogView.findViewById(R.id.compareOpLayout);
            LinearLayout actionSelectLayout = dialogView.findViewById(R.id.actionSelectLayout);
            LinearLayout paramInputLayout = dialogView.findViewById(R.id.paramInputLayout);
            LinearLayout delayInputLayout = dialogView.findViewById(R.id.delayInputLayout);


            String[] types = {"条件", "动作"};
            String[] compareOps =  Arrays.stream(CompareOp.values())
                    .map(c->c.displayName)
                    .toArray(String[]::new);
            String[] actionOptions = Arrays.stream(ActionType.values())
                    .map(a->a.displayName)
                    .toArray(String[]::new);


            String[] targetParams = new String[pathStack.size()];
            targetParams[0] = "全文";
            for (int i = 1; i < pathStack.size(); i++) {
                targetParams[i] = pathStack.get(i).varName;
            }


            typeSpinner.setAdapter(new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, types));
            compareOpSpinner.setAdapter(new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, compareOps));
            targetSpinner.setAdapter(new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, targetParams));

            ArrayAdapter<String> actionAdapter = new ArrayAdapter<>(getContext(),
                    android.R.layout.simple_spinner_item, actionOptions);
            actionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            actionSelectSpinner.setAdapter(actionAdapter);


            // 递归处理子项
            Set<String> varSet = new HashSet<>();
            List<LogicItem> children = contextData.getRoot().children;
            if (children != null && !children.isEmpty()) {
                for (LogicItem child : children) {
                    varSet.add(child.varName);
                }
            }

            // 初始化显示
            if (itemToEdit != null) {
                typeSpinner.setSelection(itemToEdit.type == LogicItem.Type.CONDITION ? 0 : 1);
                int targetIndex = Arrays.asList(targetParams).indexOf(itemToEdit.target);
                targetSpinner.setSelection(targetIndex);
                variableName.setText(itemToEdit.varName);
                paramInput.setText(itemToEdit.param);
                delayInput.setText(formatDouble(itemToEdit.delay));
                if (itemToEdit.compareOp != null) {
                    int index = Arrays.asList(compareOps).indexOf(itemToEdit.compareOp);
                    if (index >= 0) compareOpSpinner.setSelection(index);
                }
                if (itemToEdit.actionType != null) {
                    int index = Arrays.asList(actionOptions).indexOf(itemToEdit.actionType);
                    if (index >= 0) actionSelectSpinner.setSelection(index);
                }
            }
            // 根据类型切换显示控件
            typeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if (position == 0) { // 条件
                        variableLayout.setVisibility(View.VISIBLE);
                        compareOpLayout.setVisibility(View.VISIBLE);
                        compareOpSpinner.setVisibility(View.VISIBLE);
                        actionSelectLayout.setVisibility(View.GONE);
                        paramInput.setVisibility(View.VISIBLE);
                        paramInputLayout.setVisibility(View.VISIBLE);
                        delayInputLayout.setVisibility(View.GONE);
                    } else { // 动作
                        variableLayout.setVisibility(View.GONE);
                        compareOpLayout.setVisibility(View.GONE);
                        compareOpSpinner.setVisibility(View.GONE);
                        paramInput.setVisibility(View.GONE);
                        actionSelectLayout.setVisibility(View.VISIBLE);
                        paramInputLayout.setVisibility(View.GONE);
                        delayInputLayout.setVisibility(View.VISIBLE);
                    }
                }
                public void onNothingSelected(AdapterView<?> parent) {}
            });

            positiveButton.setOnClickListener(v -> {
                String type = (String) typeSpinner.getSelectedItem();
                String target = (String) targetSpinner.getSelectedItem();
                String param = paramInput.getText().toString().trim();
                String varName = variableName.getText().toString().trim();
                String compareOp = (String) compareOpSpinner.getSelectedItem();
                String actionType = (String) actionSelectSpinner.getSelectedItem();
                String delay = delayInput.getText().toString().trim();


                LogicItem.Type itemType = type.equals("条件") ? LogicItem.Type.CONDITION : LogicItem.Type.ACTION;


                if (itemType == LogicItem.Type.CONDITION) {
                    varName = "NotNumber";
                    for (int i = 0; i < 100; i++) {
                        String id = generateRandomAlphaNumeric();
                        int len = Math.min(param.length(),2);
                        String name = param.substring(0, len)+"#"+id;
                        if(!varSet.contains(name)){
                            varName = name;
                        }
                    }
                }

                if (itemToEdit == null) {
                    LogicItem newItem = new LogicItem(itemType, param, varName);
                    if (itemType == LogicItem.Type.CONDITION) {
                        newItem.compareOp = compareOp;
                    } else {
                        newItem.actionType = actionType;
                        newItem.delay = delay.trim().isEmpty() ? 0.0 : Double.parseDouble(delay.trim());
                    }
                    contextData.getCurrentList().add(newItem);
                    newItem.target = target;

                } else {
                    itemToEdit.type = itemType;
                    itemToEdit.param = param;
                    itemToEdit.varName = varName;
                    itemToEdit.target = target;
                    itemToEdit.compareOp = itemType == LogicItem.Type.CONDITION ? compareOp : null;
                    itemToEdit.actionType = itemType == LogicItem.Type.ACTION ? actionType : null;
                    itemToEdit.delay = Double.valueOf(delay);
                    if (!itemToEdit.isFolder()) itemToEdit.children.clear();
                }
                contextData.saveConfigForApp();
                renderList();
                dialog.dismiss();
            });
        });

        dialog.show();
    }

    public static String formatDouble(double value) {
        DecimalFormat df = new DecimalFormat("0.##"); // 最多保留2位小数，末尾0自动去除
        return df.format(value);
    }

    public static String generateRandomAlphaNumeric() {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 2; i++) {
            int index = random.nextInt(chars.length());
            sb.append(chars.charAt(index));
        }
        return sb.toString();
    }

    public void updateView() {
        pathStack.clear();
        pathStack.add(contextData.getRoot());
        renderPath();
        renderList();
    }
}
